package cn.itcast.client;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import cn.itcast.message.ChatRequestMessage;
import cn.itcast.message.GroupChatRequestMessage;
import cn.itcast.message.GroupCreateRequestMessage;
import cn.itcast.message.GroupJoinRequestMessage;
import cn.itcast.message.GroupMembersRequestMessage;
import cn.itcast.message.GroupQuitRequestMessage;
import cn.itcast.message.LoginRequestMessage;
import cn.itcast.message.LoginResponseMessage;
import cn.itcast.message.PingMessage;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProcotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        Scanner scanner = new Scanner(System.in);
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        AtomicBoolean EXIT = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    //ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                 // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 3s 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
//                                log.debug("3s 没有写数据了，发送一个心跳包");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {

                    	// 在连接建立后触发 active 事件
						@Override
						public void channelActive(ChannelHandlerContext ctx) throws Exception {
							new Thread(()->{
								System.out.println("请输入用户名:");
								if(EXIT.get()){
                                    return;
                                }
								String username = scanner.nextLine();
	
								System.out.println("请输入密码:");
								if(EXIT.get()){
                                    return;
                                }
								String password = scanner.nextLine();
								LoginRequestMessage message = new LoginRequestMessage(username, password);
								ctx.writeAndFlush(message);
								
								System.out.println("等待后续操作...");
								
								try {
									WAIT_FOR_LOGIN.await(); //等待登录响应返回
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								
								//登录失败，退出
								if(!LOGIN.get()) {
									ctx.channel().close(); //关闭channel，将会通知closeFuture
									return;
								}
								
								//登录成功
								while (true) {
									if(EXIT.get()){
	                                    return;
	                                }
									System.out.println("==================================");
									System.out.println("send [username] [content]");
									System.out.println("gsend [group name] [content]");
									System.out.println("gcreate [group name] [m1,m2,m3...]");
									System.out.println("gmembers [group name]");
									System.out.println("gjoin [group name]");
									System.out.println("gquit [group name]");
									System.out.println("quit");
									System.out.println("==================================");
									String command = null;
									command = scanner.nextLine();
									String[] s = command.split(" ");
                                    switch (s[0]){
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                                            break;
                                        case "gcreate":
                                            Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                            set.add(username); // 加入自己
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }
									
								}
								
							},"system in").start();
							
						}

						@Override
						public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
							log.debug("msg: {}", msg);
							if(msg instanceof LoginResponseMessage) {
								LoginResponseMessage message = (LoginResponseMessage)msg;
								if(message.isSuccess()) {
									LOGIN.set(true);
								}
								 // 唤醒 system in 线程
								WAIT_FOR_LOGIN.countDown();
							}
							
						}
						
						// 在连接断开时触发
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开，按任意键退出..");
                            EXIT.set(true);
                        }
						
                        // 在出现异常时触发
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
                            EXIT.set(true);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
